﻿using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Text;
using System.Reflection;
using System.Collections;
using WCS.Utils;
using WCS.WebRequest;
using WcsTask.DevCommTaks;
using WCS.Controls.RunLog;
using WCS.Helpers;
using WCS.Entity;
using Sunny.UI;
using System.Linq;
using SqlSugar;
using System.Configuration;
using WCS.Entity.MES;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using SqlSugar.Extensions;

namespace WcsTask
{
    /// <summary>
    /// 输送线任务处理实体
    /// </summary>
    public class ConveyorTask
    {
        private ConveyorTask() { }

        private static readonly ConveyorTask conveyorTask = new ConveyorTask();

        public static ConveyorTask _conveyorTask
        {
            get
            {
                return conveyorTask;
            }
        }

        /// <summary>
        /// 日志模块
        /// </summary>
        string _modular = "【输送线任务模块】";

        /// <summary>
        /// 数据库连接对象
        /// </summary>
        static SqlSugarDapper SqlSugarDapper = SqlSugarDapper.GetDbContext();

        /// <summary>
        /// 仿真模式
        /// </summary>
        string _simulation = ConfigurationManager.AppSettings["simulation"];

        /// <summary>
        /// mes接口
        /// </summary>
        readonly string _MES = ConfigurationManager.AppSettings["MES"];

        readonly string _MESTrayStatus = ConfigurationManager.AppSettings["MESTrayStatus"];

        /// <summary>
        /// 输送线任务集合
        /// </summary>
        public List<WcsTaskConveyor> wcsTaskConveyorList
        {
            get
            {
                var list = SqlSugarDapper.DB.SqlQueryable<WcsTaskConveyor>("SELECT * from WCS_TASK_CONVEYOR where TASK_CODE in (SELECT TASK_CODE from WCS_TASK_Main where TASK_STATE <> 102) ORDER BY PRIORITY, sub_Taskcode").ToList();
                return list;
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            ConveyProcessTask();
        }

        /// <summary>
        /// 输送线任务状态处理
        /// </summary>
        public void ConveyProcessTask()
        {
            while (true)
            {
                try
                {
                    var wcsTaskMainList = ProcessingTaskMain._processingTaskMain._wcsTaskMains.FindAll(f => f.wcsTaskConveyor != null);

                    var wcsTaskMainListgroup = wcsTaskMainList.GroupBy(g => g.MaterialType).ToList();


                    foreach (var wcsTaskMain in wcsTaskMainList.FindAll(w => w.Task_Type == "in"))
                    {
                        if (wcsTaskMain.wcsTaskConveyor.Task_State == (int)Task_State.等待执行)
                        {
                            ConveyTaskSends(wcsTaskMain.wcsTaskConveyor);
                        }
                    }

                    foreach (var wcsTaskMain in wcsTaskMainList.FindAll(w => w.Task_Type == "out"))
                    {
                        if (wcsTaskMain.wcsTaskConveyor.Task_State == (int)Task_State.等待执行)
                        {
                            //if (wcsTaskMainListgroup.Count > 1)
                            //{
                            //    var asd = wcsTaskConveyorList.Find(f => f.Task_Type == "out" && f.MaterialType != wcsTaskMain.wcsTaskConveyor.MaterialType && f.Start_Station == f.Current_Station && f.Task_State == 55);
                            //    if (asd != null)
                            //    {
                            //        break;
                            //    }
                            //}

                            ConveyTaskSends(wcsTaskMain.wcsTaskConveyor);
                        }
                    }

                    foreach (var wcsTaskMain in wcsTaskMainList)
                    {
                        if (wcsTaskMain.wcsTaskConveyor.Task_State == (int)Task_State.执行中)
                        {
                            //任务超过60分钟还未上报完成自动完成任务
                            //仿真模式 任务报完成
                            var minutes = (DateTime.Now - wcsTaskMain.wcsTaskConveyor.CreateTime.ObjToDate()).Minutes;
                            if (minutes >= 60 || _simulation == "1")
                            {
                                ConveyTaskFeedbackResult(wcsTaskMain.wcsTaskConveyor.Sub_TaskCode);
                            }
                        }
                        if (wcsTaskMain.wcsTaskConveyor.Task_State == (int)Task_State.任务完成)
                        {
                            ConveyTaskComplete(wcsTaskMain.wcsTaskConveyor);
                        }
                    }
                }
                catch (Exception ex)
                {
                    RunLog.runLog.Error($"{_modular} 异常信息【{ex.Message}】【{ex.StackTrace}】");
                }
                Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// 主任务拆分输送线任务
        /// </summary>
        public bool MainTaskSplitConveyTask(WcsTaskMain wcsTaskMain, WcsRoute NextRoute)
        {
            try
            {
                //声明子任务实体
                WcsTaskConveyor wcsTaskConveyor = new WcsTaskConveyor
                {
                    Id = Guid.NewGuid().ToString(),
                    Task_Code = wcsTaskMain.Task_Code,//主任务号
                    Sub_TaskCode = ProcessingTaskMain.GenerateRandomCode("sub"),//子任务号 自己生成 //获取流水号
                    TrayBar_Code = wcsTaskMain.TrayBar_Code,//托盘号
                    Task_Source = wcsTaskMain.Task_Source,//任务来源
                    Start_Station = wcsTaskMain.Current_Station,//起始位置
                    End_Station = NextRoute.Next_Station,//目标位置
                    Current_Station = wcsTaskMain.Current_Station,//当前位置
                    WMSEndStation = wcsTaskMain.End_Station,//当前位置
                    Task_State = (int)Task_State.等待执行,//任务状态
                    Task_Type = wcsTaskMain.Task_Type,//任务类型
                    MaterialType = wcsTaskMain.MaterialType,//任务类型
                    brother = wcsTaskMain.brother,//任务类型
                    Perform = NextRoute.Start_Station,//执行设备
                    Priority = wcsTaskMain.Priority,//优先级
                    TaskTips = "",
                    CreateTime = DateTime.Now//创建时间

                };

                if (wcsTaskConveyor.Task_Type == "in")
                {
                    wcsTaskConveyor.WMSBinCode = wcsTaskMain.EndWMSBinCode;//入库显示结束位置
                }
                if (wcsTaskConveyor.Task_Type == "out")
                {
                    wcsTaskConveyor.WMSBinCode = wcsTaskMain.StartWMSBinCode;//出库显示起始位置
                }

                RunLog.runLog.Debug($"{_modular}输送线任务拆分成功 主任务号【{wcsTaskMain.Task_Code}】 子任务号【{wcsTaskConveyor.Sub_TaskCode}】 托盘号【{wcsTaskConveyor.TrayBar_Code}】");

                //添加任务
                SqlSugarDapper.DB.Insertable(wcsTaskConveyor).ExecuteCommand();

                return true;
            }
            catch (Exception ex)
            {
                RunLog.runLog.Error($"{_modular} 异常信息【{ex.Message}】【{ex.StackTrace}】");
                return false;
            }
        }

        /// <summary>
        /// 输送线任务下发
        /// </summary>
        /// <param name="wcsTaskConveyor"></param>
        public void ConveyTaskSends(WcsTaskConveyor wcsTaskConveyor)
        {
            try
            {
                if (!wcsTaskConveyor.TaskTips.Contains($"准备下发输送线任务"))
                {
                    //更新任务提示
                    SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                         .SetColumns(w => w.TaskTips == w.TaskTips + $"准备下发输送线任务")
                         .Where(w => w.Task_Code == wcsTaskConveyor.Task_Code).ExecuteCommand();

                    RunLog.runLog.Debug($"{_modular} 准备下发输送线任务，任务号:【{wcsTaskConveyor.Task_Code}】输送线任务号:【{wcsTaskConveyor.Sub_TaskCode}】托盘号【{wcsTaskConveyor.TrayBar_Code}】");
                }

                //根据站台号找到对应站台和所属PLC
                var plcDevStation = (ConveyorStation)PlcDev._plcDev.GetStationNo(wcsTaskConveyor.Perform);
                if (plcDevStation == null)
                {
                    RunLog.runLog.Warning($"{_modular} 未找到【{wcsTaskConveyor.Perform}】站台");
                    return;
                }

                //实例化发送对象
                ConveyWriteData conveyWriteData = new ConveyWriteData()
                {
                    TaskCode = wcsTaskConveyor.Sub_TaskCode,
                    TrayBarCode = wcsTaskConveyor.TrayBar_Code,
                    WMSBinCode = wcsTaskConveyor.WMSBinCode,
                };

                if (wcsTaskConveyor.Task_Type == "in")
                {
                    conveyWriteData.EndWarhouse = wcsTaskConveyor.End_Station;

                    var warehouseId = 0;
                    var add = "";

                    if (wcsTaskConveyor.End_Station == "9001")
                    {
                        warehouseId = (100 + Convert.ToInt32(wcsTaskConveyor.WMSBinCode));
                    }
                    else if (wcsTaskConveyor.End_Station == "9002")
                    {
                        warehouseId = (200 + Convert.ToInt32(wcsTaskConveyor.WMSBinCode));
                    }

                    if (wcsTaskConveyor.Current_Station == "A002")
                    {
                        add = "DB48.24";
                    }
                    else if (wcsTaskConveyor.Current_Station == "A006")
                    {
                        add = "DB48.28";
                    }

                    //首先创建一个数组
                    byte[] writeBytes = new byte[4];

                    BitConverter.GetBytes(Convert.ToInt16(warehouseId)).Reverse().ToArray().CopyTo(writeBytes, 0);
                    BitConverter.GetBytes(Convert.ToInt16(wcsTaskConveyor.Sub_TaskCode)).Reverse().ToArray().CopyTo(writeBytes, 2);

                    //给设备下发任务任务
                    if (!PlcDev._plcDev.s7Plc.S7PlcWiter(add, writeBytes).IsSuccess)
                    {
                        //更任务的任务提示
                        SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                         .SetColumns(w => w.TaskTips == w.TaskTips + $"下发任务失败")
                         .Where(w => w.Sub_TaskCode == wcsTaskConveyor.Sub_TaskCode).ExecuteCommand();

                        RunLog.runLog.Warning($"{_modular} 下发任务失败【{wcsTaskConveyor.Task_Code}】");

                        return;
                    }

                    //入库保存PLC任务信息
                    SendPLCCode.AddSendPLCInfo(new SendPLCCode
                    {
                        taskCode = wcsTaskConveyor.Sub_TaskCode,
                        barCode = wcsTaskConveyor.TrayBar_Code,
                        wareHourseCode = warehouseId.ToString(),
                        CreateTime = DateTime.Now,
                        task_type = "入库"
                    });

                    RunLog.runLog.Debug($"入库任务给PLC下发成功，站台【{plcDevStation.Station_Plc_No}】入库位置【{warehouseId}】 任务号【{wcsTaskConveyor.Sub_TaskCode}】");
                }
                if (wcsTaskConveyor.Task_Type == "out")
                {
                    //var warehouseInfo = SqlSugarDapper.DB.Queryable<WarehouseInfo>().Where(w => w.barCode == wcsTaskConveyor.TrayBar_Code && w.ID == $"{wcsTaskConveyor.Start_Station}-{wcsTaskConveyor.WMSBinCode}").First();
                    //WarehouseInfo.ChangeWarehouseInfo(warehouseInfo, (int)StationState.出库占用);
                    //判断已下发任务数量是否过多
                    var taskQty = SqlSugarDapper.DB.Queryable<WcsTaskConveyor>().Where(w => w.Task_State == (int)Task_State.执行中 && w.Task_Type == "out" && w.Current_Station == wcsTaskConveyor.Start_Station).First();
                    if (taskQty != null)
                    {
                        if (!wcsTaskConveyor.TaskTips.Contains($"提升机已有任务"))
                        {
                            //更新任务提示
                            SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                                 .SetColumns(w => w.TaskTips == w.TaskTips + $"提升机已有任务")
                                 .Where(w => w.Task_Code == wcsTaskConveyor.Task_Code).ExecuteCommand();

                            RunLog.runLog.Warning($"{_modular}，提升机已有任务");
                        }

                        return;
                    }

                    var taskQty2 = SqlSugarDapper.DB.Queryable<WcsTaskConveyor>().Where(w => w.Task_State == (int)Task_State.等待执行 && w.Task_Type == "out" && w.Current_Station == wcsTaskConveyor.Start_Station).OrderBy(w => w.CreateTime, OrderByType.Asc).ToList().First();
                    if (taskQty2.Sub_TaskCode != wcsTaskConveyor.Sub_TaskCode)
                    {
                        if (!wcsTaskConveyor.TaskTips.Contains($"提升机已有任务"))
                        {
                            //更新任务提示
                            SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                                 .SetColumns(w => w.TaskTips == w.TaskTips + $"提升机已有任务")
                                 .Where(w => w.Task_Code == wcsTaskConveyor.Task_Code).ExecuteCommand();

                            RunLog.runLog.Warning($"{_modular}，当前等待执行的任务不是最先的任务");
                        }
                        return;
                    }
                    //读取任务号
                    var con = Convert.ToInt16(PlcDev._plcDev.s7Plc?.S7PlcReadInt("DB48.14", 2).Content);

                    if (con != 0)
                    {
                        RunLog.runLog.Warning($"{wcsTaskConveyor.Current_Station}，有任务残留，暂不下发任务 任务号【{wcsTaskConveyor.Sub_TaskCode}】");
                        return;
                    }

                    //出库位置发给PLC
                    var warehouseId = "";

                    if (wcsTaskConveyor.Current_Station == "9001")
                    {
                        warehouseId = (100 + Convert.ToInt32(wcsTaskConveyor.WMSBinCode)).ToString();
                    }
                    else if (wcsTaskConveyor.Current_Station == "9002")
                    {
                        var warehouse = SqlSugarDapper.DB.Queryable<Warehouse>().Where(w => w.ID == $"{wcsTaskConveyor.Current_Station}-{wcsTaskConveyor.WMSBinCode}").First();

                        if (warehouse.IsFullMaterial == 0)
                        {
                            //判断9002是否有任务正在执行
                            var task = SqlSugarDapper.DB.Queryable<WcsTaskConveyor>().Where(w => w.Task_Type == "out" && w.Start_Station == "9001" && w.End_Station == "B007").ToList();
                            if (task.Count != 0)
                            {
                                RunLog.runLog.Warning($"9001有B002的提升机任务，暂不下发新任务 任务号【{wcsTaskConveyor.Sub_TaskCode}】");
                                return;
                            }
                        }

                        warehouseId = (200 + Convert.ToInt32(wcsTaskConveyor.WMSBinCode)).ToString();
                    }

                    if (_simulation == "0")
                    {
                        //下发PLC出库任务
                        var readBytes = PlcDev._plcDev.s7Plc.S7PlcRead("DB47.8", Convert.ToUInt16(1));
                        var pLCState = PlcDev._plcDev.Byte_BitToString(readBytes.Content.Take(1).ToArray());
                        if (pLCState[0] == '0')
                        {
                            var end = wcsTaskConveyor.End_Station == "B001" ? 1 : 2;
                            byte[] warehouseIdbytes = BitConverter.GetBytes(Convert.ToInt16(warehouseId)).Reverse().ToArray();
                            byte[] taskBytes = BitConverter.GetBytes(Convert.ToUInt16(wcsTaskConveyor.Sub_TaskCode)).Reverse().ToArray();
                            byte[] endB = BitConverter.GetBytes(Convert.ToUInt16(end)).Reverse().ToArray();
                            byte[] barCode = Encoding.ASCII.GetBytes("$$" + wcsTaskConveyor.TrayBar_Code);

                            PlcDev._plcDev.s7Plc.S7PlcWiter("DB48.10", warehouseIdbytes);
                            PlcDev._plcDev.s7Plc.S7PlcWiter("DB48.14", taskBytes);
                            PlcDev._plcDev.s7Plc.S7PlcWiter("DB48.12", endB);
                            // PlcDev._plcDev.s7Plc.S7PlcWiter("DB48.32", barCode);
                            PlcDev._plcDev.s7Plc.S7PlcWiterString("DB48.32", wcsTaskConveyor.TrayBar_Code);

                            //出库保存PLC任务信息
                            SendPLCCode.AddSendPLCInfo(new SendPLCCode
                            {
                                taskCode = wcsTaskConveyor.Sub_TaskCode,
                                barCode = wcsTaskConveyor.TrayBar_Code,
                                wareHourseCode = warehouseId,
                                CreateTime = DateTime.Now,
                                task_type = "出库"
                            });

                            RunLog.runLog.Debug($"出库任务给PLC下发成功，出库位置【{warehouseId}】 任务号【{wcsTaskConveyor.Sub_TaskCode}】托盘码【{wcsTaskConveyor.TrayBar_Code}】");
                        }
                    }

                    if (Warehouse.IsPushMes($"{wcsTaskConveyor.Current_Station}-{wcsTaskConveyor.WMSBinCode}").IsFullMaterial == 1)
                    {
                        var resultTrayStatus = HttpRequest.httpRequest.WebGetRequestMES(wcsTaskConveyor.TrayBar_Code, "http://10.3.15.130:8090/apis/Acc/ProductProcess/TrayStatus?trayCode=");

                        if (resultTrayStatus != null && resultTrayStatus.data.trayResultDesc == "砂芯入库")
                        {
                            //查询是否是
                            var existCode = SqlSugarDapper.DB.Queryable<WarehouseInfo>()
                                .Where(w => w.barCode == wcsTaskConveyor.TrayBar_Code)
                                .First();
                            //上报MES
                            MESWriteData mESWriteData = new MESWriteData()
                            {
                                MachineId = 129051,
                                MachineType = 501,
                                //ProductId = 6475,
                                ActionTypeId = 2,

                                data = new Data
                                {
                                    TrayCode = wcsTaskConveyor.TrayBar_Code,
                                    Params = new List<Params>()
                                }
                            };
                            mESWriteData.data.Params.Add(new Params()
                            {
                                ParamType = "TemperatureTop",
                                ParamValue = PlcDev._plcDev._Temperature.Max() + "℃",
                                Position = "",
                                Result = 1
                            });
                            mESWriteData.data.Params.Add(new Params()
                            {
                                ParamType = "TemperatureLowest",
                                ParamValue = PlcDev._plcDev._Temperature.Min() + "℃",
                                Position = "",
                                Result = 1
                            });
                            mESWriteData.data.Params.Add(new Params()
                            {
                                ParamType = "HumidityTop",
                                ParamValue = PlcDev._plcDev._Humidity.Max() + "%",
                                Position = "",
                                Result = 1
                            });
                            mESWriteData.data.Params.Add(new Params()
                            {
                                ParamType = "HumidityLowest",
                                ParamValue = PlcDev._plcDev._Humidity.Min() + "%",
                                Position = "",
                                Result = 1
                            });
                            mESWriteData.data.Params.Add(new Params()
                            {
                                ParamType = "InStockTime",
                                ParamValue = existCode == null ? "" : (DateTime.Now - existCode.CreateTime.ToString().ToDateTime()).ToString(),
                                Position = "",
                                Result = 1
                            });

                            var result = HttpRequest.httpRequest.WebPostRequestMES(JsonConvert.SerializeObject(mESWriteData), _MES);
                            if (result.ret == 1 && existCode != null)
                            {
                                RunLog.runLog.InfoMES($@"【出库上报】上传MES成功 成功信息【{result.data}】托盘码：{wcsTaskConveyor.TrayBar_Code}最高温度：{PlcDev._plcDev._Temperature.Max()},最低温度:{PlcDev._plcDev._Temperature.Min()}最高湿度{PlcDev._plcDev._Humidity.Min()}最低湿度:{PlcDev._plcDev._Humidity.Min()}【JSON】{JsonConvert.SerializeObject(mESWriteData)}");
                            }
                            else
                            {
                                RunLog.runLog.InfoMES($@"【出库上报】上传MES失败 失败信息【{result.data}】托盘码{wcsTaskConveyor.TrayBar_Code}【JSON】{JsonConvert.SerializeObject(mESWriteData)}");
                            }
                        }
                        else
                        {
                            RunLog.runLog.InfoMES($@"【出库上报托盘状态异常】托盘状态【{resultTrayStatus?.data.trayResultDesc}】托盘码【{wcsTaskConveyor?.TrayBar_Code}】");
                        }
                    }
                }

                //更任务的任务提示
                //更新子任务状态成执行中
                SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                     .SetColumns(w => new WcsTaskConveyor()
                     {
                         TaskTips = $"下发成功，等待设备【{plcDevStation.Station_Plc_No}】执行完成",
                         Task_State = (int)Task_State.执行中,
                         SendTime = DateTime.Now,
                     })
                     .Where(w => w.Sub_TaskCode == wcsTaskConveyor.Sub_TaskCode)
                     .ExecuteCommand();

                //更新主任务状态
                SqlSugarDapper.DB.Updateable<WcsTaskMain>()
                     .SetColumns(w => w.Task_State == (int)Task_State.执行中)
                     .Where(w => w.Task_Code == wcsTaskConveyor.Task_Code)
                     .ExecuteCommand();
            }
            catch (Exception ex)
            {
                RunLog.runLog.Error($"{_modular} 异常信息【{ex.Message}】【{ex.StackTrace}】");
            }
        }

        /// <summary>
        /// 十层提升机处理输送线任务
        /// </summary>
        /// <param name="taskCode"></param>
        public bool ElevatorTaskFeedbackResult(string taskCode)
        {
            try
            {
                var wcsTaskConveyor = wcsTaskConveyorList.Find(w => w.Sub_TaskCode == taskCode);
                if (wcsTaskConveyor != null)
                {
                    RunLog.runLog.Debug($@"出库十层提升机上报任务完成 任务号【{taskCode}】托盘码【{wcsTaskConveyor.TrayBar_Code}】");

                    var info = WarehouseInfo.GetWarehouseInfoByBarCode(wcsTaskConveyor.TrayBar_Code, wcsTaskConveyor.Start_Station + "-" + wcsTaskConveyor.WMSBinCode);

                    if (info == null)
                    {
                        RunLog.runLog.Debug($"任务号：{taskCode}条码：{wcsTaskConveyor.TrayBar_Code}没找到库存");
                        //更新输送线任务当前位置
                        //更新输送线任务状态
                        SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                         .SetColumns(w => w.Current_Station == wcsTaskConveyor.End_Station)
                         .Where(w => w.Sub_TaskCode == wcsTaskConveyor.Sub_TaskCode).ExecuteCommand();

                        //更新主任务当前位置
                        SqlSugarDapper.DB.Updateable<WcsTaskMain>()
                        .SetColumns(w => w.Current_Station == wcsTaskConveyor.End_Station)
                        .Where(w => w.Task_Code == wcsTaskConveyor.Task_Code).ExecuteCommand();
                        return false;
                    }

                    RunLog.runLog.Debug($"info状态{info.ID}");
                    RunLog.runLog.Debug($"info状态{info.index}");
                    RunLog.runLog.Debug($"info状态{info.barCode}");
                    RunLog.runLog.Debug($"info状态{info.state}");

                    var deleteNum = WarehouseInfo.DeleteWarehouseInfo(info);

                    RunLog.runLog.Debug($@"删除库存 托盘码【{wcsTaskConveyor.TrayBar_Code}】删除记录【{deleteNum}】");

                    //更新输送线任务当前位置
                    //更新输送线任务状态
                    SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                     .SetColumns(w => w.Current_Station == wcsTaskConveyor.End_Station)
                     .Where(w => w.Sub_TaskCode == wcsTaskConveyor.Sub_TaskCode).ExecuteCommand();

                    //更新主任务当前位置
                    SqlSugarDapper.DB.Updateable<WcsTaskMain>()
                    .SetColumns(w => w.Current_Station == wcsTaskConveyor.End_Station)
                    .Where(w => w.Task_Code == wcsTaskConveyor.Task_Code).ExecuteCommand();
                }
                return true;
            }
            catch (Exception ex)
            {
                RunLog.runLog.Error($"{_modular} 异常信息【{ex.Message}】【{ex.StackTrace}】");
                return false;
            }
        }

        /// <summary>
        /// 处理输送线任务
        /// </summary>
        /// <param name="taskCode"></param>
        public bool ConveyTaskFeedbackResult(string taskCode)
        {
            try
            {
                var wcsTaskConveyor = wcsTaskConveyorList.Find(w => w.Sub_TaskCode == taskCode);
                if (wcsTaskConveyor != null)
                {
                    RunLog.runLog.Debug($@"PLC上报任务完成 任务号【{taskCode}】托盘码【{wcsTaskConveyor.TrayBar_Code}】");

                    //根据站台号找到对应站台和所属PLC
                    var plcDevStation = (ConveyorStation)PlcDev._plcDev.GetStationNo(wcsTaskConveyor.Perform);

                    //更新主任务当前位置
                    SqlSugarDapper.DB.Updateable<WcsTaskMain>()
                            .SetColumns(w => w.Current_Station == wcsTaskConveyor.End_Station)
                            .Where(w => w.Task_Code == wcsTaskConveyor.Task_Code)
                            .ExecuteCommand();

                    //入库
                    if (wcsTaskConveyor.End_Station == "9001" || wcsTaskConveyor.End_Station == "9002")
                    {
                        //获取当前层数的最后Index
                        var i = WarehouseInfo.GetWarehouseInfoIndex($"{wcsTaskConveyor.End_Station}-{wcsTaskConveyor.WMSBinCode}");

                        SqlSugarDapper.DB.Updateable<WarehouseInfo>()
                            .SetColumns(w => w.state == (int)StationState.在库)
                            .SetColumns(w => w.index == i)
                            .SetColumns(w => w.CreateTime == DateTime.Now)
                            .Where(w => w.barCode == wcsTaskConveyor.TrayBar_Code && w.state == (int)StationState.入库占用 && w.ID == $"{wcsTaskConveyor.End_Station}-{wcsTaskConveyor.WMSBinCode}")
                            .ExecuteCommand();
                    }

                    if (wcsTaskConveyor.Start_Station == "9001" || wcsTaskConveyor.Start_Station == "9002")
                    {
                        var info = WarehouseInfo.GetWarehouseInfoByBarCode(wcsTaskConveyor.TrayBar_Code, wcsTaskConveyor.Start_Station + "-" + wcsTaskConveyor.WMSBinCode);
                        if (info != null)
                        {
                            var deleteNum = WarehouseInfo.DeleteWarehouseInfo(info);

                            //删除完成读取是否还有托盘
                            if (WarehouseInfo.GetWarehouseInfoIndex(wcsTaskConveyor.Start_Station + "-" + wcsTaskConveyor.WMSBinCode) == 1)
                            {
                                var warehouse = Warehouse.GetWarehouse(wcsTaskConveyor.Start_Station + "-" + wcsTaskConveyor.WMSBinCode);

                                if (!warehouse.NextMaterialType.IsNullOrEmpty())
                                {
                                    var NextMaterialTypeAncIsNull = warehouse.NextMaterialType.Split(",");
                                    string NextMaterialType = NextMaterialTypeAncIsNull[0];
                                    var sql = SqlSugarDapper.DB.Updateable<Warehouse>()
                                        .SetColumns(s => s.IsIN == 1)
                                        .SetColumns(s => s.MaterialType == NextMaterialType)
                                        .SetColumns(s => s.NextMaterialType == "")
                                        .Where(w => w.ID == warehouse.ID);
                                    if (NextMaterialTypeAncIsNull.Length >= 2)
                                    {
                                        int IsFullMaterial = Convert.ToInt16(NextMaterialTypeAncIsNull[1]);
                                        sql.SetColumns(s => s.IsFullMaterial == IsFullMaterial);
                                    }
                                    sql.ExecuteCommand();
                                }
                            }
                        }
                    }

                    //更任务的任务提示
                    //更新输送线任务当前位置
                    //更新输送线任务状态
                    SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                     .SetColumns(w => new WcsTaskConveyor()
                     {
                         Current_Station = wcsTaskConveyor.End_Station,
                         Task_State = (int)Task_State.任务完成,
                         CompleteTime = DateTime.Now,
                     })
                    .Where(w => w.Sub_TaskCode == wcsTaskConveyor.Sub_TaskCode).ExecuteCommand();

                    //ConveyTaskComplete(wcsTaskConveyor);
                }
                return true;
            }
            catch (Exception ex)
            {
                RunLog.runLog.Error($"{_modular} 异常信息【{ex.Message}】【{ex.StackTrace}】");
                return false;
            }
        }

        /// <summary>
        /// 输送线任务完成
        /// </summary>
        /// <param name="end_Station"></param>
        /// <param name="conveyTask"></param>
        private void ConveyTaskComplete(WcsTaskConveyor wcsTaskConveyor)
        {
            try
            {
                RunLog.runLog.Debug($"{_modular} 输送线任务完成,删除任务，任务号:【{wcsTaskConveyor.Sub_TaskCode}】");

                var sqlSetColumns = SqlSugarDapper.DB.Updateable<WcsTaskMain>()
                     .Where(w => w.Task_Code == wcsTaskConveyor.Task_Code);

                //主任务的目标位置等于子任务的目标位置  任务完成
                if (wcsTaskConveyor.WMSEndStation == wcsTaskConveyor.End_Station)
                {
                    //更新主任务状态成上报WMS完成


                    //更新主任务提示
                    sqlSetColumns.SetColumns(w => w.Task_State == (int)Task_State.上报WMS任务完成);

                    RunLog.runLog.Debug($"{_modular} 主任务结束位置和当前站台一致任务完成 【{wcsTaskConveyor.Task_Code}】");
                }
                else
                {
                    //更新主任务提示
                    //把主任务更改为可拆分状态
                    sqlSetColumns.SetColumns(w => w.TaskTips == "准备拆分下一段任务");

                    var readStation = PlcDev._plcDev.wcsReadTrayCodeList.Find(t => t.Station_Plc_No == wcsTaskConveyor.End_Station);

                    //如果目标位置是扫码站台的话 暂不拆分任务
                    if (readStation != null)
                    {
                        sqlSetColumns.SetColumns(w => w.Split == 0);
                    }
                    else if (wcsTaskConveyor.End_Station == "B001" || wcsTaskConveyor.End_Station == "B007")
                    {
                        //判断是否有关联任务
                        if (!wcsTaskConveyor.brother.IsNullOrEmpty())
                        {
                            //获取上一个任务
                            var endTask = ProcessingTaskMain._processingTaskMain._wcsTaskMains.Find(f => f.Task_Code == wcsTaskConveyor.brother);

                            if (endTask != null)
                            {
                                if (endTask.Current_Station == wcsTaskConveyor.End_Station)
                                {
                                    SqlSugarDapper.DB.Updateable<WcsTaskMain>()
                                        .SetColumns(w => w.TrayBar_Code == w.TrayBar_Code + "," + endTask.TrayBar_Code)
                                        .SetColumnsIF(!endTask.BarCode1Data.IsNullOrEmpty(), w => w.BarCode1Data == endTask.BarCode1Data)
                                        .SetColumnsIF(!endTask.BarCode2Data.IsNullOrEmpty(), w => w.BarCode2Data == endTask.BarCode2Data)
                                        .Where(w => w.Task_Code == wcsTaskConveyor.Task_Code)
                                        .ExecuteCommand();

                                    sqlSetColumns.SetColumns(w => w.Split == 1);
                                    //删除子任务
                                    SqlSugarDapper.DB.Deleteable<WcsTaskMain>()
                                        .Where(w => w.Task_Code == endTask.Task_Code)
                                        .ExecuteCommand();
                                }
                            }
                        }
                    }
                    else
                    {
                        sqlSetColumns.SetColumns(w => w.Split == 1);
                    }
                }
                DeleteConveyTask(wcsTaskConveyor.Task_Code, "任务执行完成");
                sqlSetColumns.ExecuteCommand();
            }
            catch (Exception ex)
            {
                RunLog.runLog.Error($"{_modular} 异常信息【{ex.Message}】【{ex.StackTrace}】");
            }
        }

        /// <summary>
        /// 删除输送线任务并加入历史记录
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="TaskCode"></param>
        public void DeleteConveyTask(string TaskCode, string TaskTips)
        {
            try
            {
                //更任务的任务提示
                SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                    .SetColumns(w => w.TaskTips == TaskTips)
                    .Where(w => w.Task_Code == TaskCode).ExecuteCommand();

                var wcsTaskConveyor = SqlSugarDapper.DB.Queryable<WcsTaskConveyor>().Where(w => w.Task_Code == TaskCode).First();

                if (wcsTaskConveyor != null)
                {
                    WcsZBKTaskConveyor wcsZBKTaskConveyor = new WcsZBKTaskConveyor();
                    wcsZBKTaskConveyor.MapperFrom(wcsTaskConveyor);
                    //添加历史记录
                    SqlSugarDapper.DB.Insertable(wcsZBKTaskConveyor).ExecuteCommand();

                    //删除子任务
                    SqlSugarDapper.DB.Deleteable<WcsTaskConveyor>()
                        .Where(w => w.Task_Code == TaskCode).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                RunLog.runLog.Error($"{_modular} 异常信息【{ex.Message}】【{ex.StackTrace}】");
            }
        }
    }
}
